import { createStore } from 'vuex'
import cart from './cart'
import order from './order'

export default createStore({
  state: {
    likedPosts: [] // 存储用户点赞的帖子
  },
  getters: {
    getLikedPosts: state => state.likedPosts,
    isPostLiked: state => postId => state.likedPosts.some(post => post.id === postId)
  },
  mutations: {
    // 添加点赞帖子
    addLikedPost(state, post) {
      // 检查是否已经点赞过
      if (!state.likedPosts.some(item => item.id === post.id)) {
        state.likedPosts.push(post);
      }
    },
    // 移除点赞帖子
    removeLikedPost(state, postId) {
      state.likedPosts = state.likedPosts.filter(post => post.id !== postId);
    }
  },
  actions: {
    // 切换点赞状态
    toggleLikePost({ commit, state }, post) {
      const isLiked = state.likedPosts.some(item => item.id === post.id);
      if (isLiked) {
        commit('removeLikedPost', post.id);
        return false; // 返回新的点赞状态
      } else {
        commit('addLikedPost', post);
        return true; // 返回新的点赞状态
      }
    }
  },
  modules: {
    cart,
    order
  }
})
